import axios from "axios";
import { ElMessage } from "element-plus";
import { userStore } from "@/stores/user";

const axiosInstance = axios.create({
	baseURL: "http://localhost:3000/api/",
});
// 请求拦截器
axiosInstance.interceptors.request.use((config) => {
	const token = localStorage.getItem("token");
	if (token) config.headers.token = token;

	return config;
});
// 响应拦截器
axiosInstance.interceptors.response.use(
	(response) => {
		// 如果为401, 则代表登录失效
		if (response.data.code === 401) {
			userStore().logout();
		}
		// 如果不为200，则代表有错误
		if (response.data.code !== 200) {
			ElMessage({ message: response.data.msg, type: "error" });
			return Promise.reject(response.data);
		}

		return response.data;
	},
	(error) => {
		if (error.code === "ERR_NETWORK") error.message = "网络错误, 请检查网络!";
		if (error.code === "ERR_BAD_REQUEST") error.message = "请求路径不存在, 请检查接口!";

		ElMessage({ message: error.message, type: "error" });
		return Promise.reject(error);
	}
);

export default axiosInstance;
